﻿#include "dispatchcore.h"
#include "global.h"

DispatchCore::DispatchCore(QObject *parent) : QObject(parent)
{

}

DispatchCore::~DispatchCore()
{
    if(pThread_ServerMonitor){
        pThread_ServerMonitor->quit();
        pThread_ServerMonitor->wait();
        pThread_ServerMonitor->deleteLater();
    }
    if(pServerMonitor != nullptr){
        pServoManager->deleteLater();
    }

    if(pThread_ServerMonitor){
        pThread_ServoManager->quit();
        pThread_ServoManager->wait();
        pThread_ServoManager->deleteLater();
    }
    if(pServoManager){
        pServoManager->deleteLater();
    }
}

void DispatchCore::InitCommDevice()
{
    pServerMonitor = new ServerMonitor();
    pServoManager = new ServoManager();
    //********************************初始化服务器监控*****************************//

    pThread_ServerMonitor = new QThread(this);
    connect(pThread_ServerMonitor,SIGNAL(started()),pServerMonitor,SLOT(slot_init()));
    connect(pServerMonitor, SIGNAL(sig_ServerCommandReady(QJsonObject)), this, SLOT(slot_ServerCommandAnalysis(QJsonObject)));
    connect(pServoManager,SIGNAL(sig_SendServoData(QJsonObject)),pServerMonitor,SLOT(slot_sendDataToServer(QJsonObject)));
    connect(pServoManager,SIGNAL(sig_imgResultToServer(QImage)),pServerMonitor,SLOT(slot_imgResultToServer(QImage)));
    //********************************定义电机管理类及其线程//********************************

    pThread_ServoManager = new QThread(this);
    connect(pThread_ServoManager,SIGNAL(started()),pServoManager,SLOT(slot_InitDevice()));
    connect(this,SIGNAL(sig_SetServoParam(uint8_t,int32_t,int32_t)),pServoManager,SLOT(slot_SetServoParam(uint8_t,int32_t,int32_t)));
    connect(this,SIGNAL(sig_ReadRwParams(uint8_t)),pServoManager,SLOT(slot_ReadRwParams(uint8_t)));
    connect(this,SIGNAL(sig_moveCmd(QJsonObject)),pServoManager,SLOT(slot_MoveCmd(QJsonObject)));
    connect(this,SIGNAL(sig_startInOutCabCmd()),pServoManager,SLOT(slot_startInOutCabCmd()));
    connect(this,SIGNAL(sig_startQRLocateCmd()),pServoManager,SLOT(slot_startQRLocateCmd()));
    connect(this,SIGNAL(sig_imgCmd()),pServoManager,SLOT(slot_imgCmd()));

    pServoManager->moveToThread(pThread_ServoManager);

    pThread_ServerMonitor->start();
    pThread_ServoManager->start();
}

void DispatchCore::SignalHandler(int signum)
{
    mylog << "Interrupt signal (" << signum << ") received.\n";

    pServoManager->SetServoAllMNT_PreOper();
    // 清理并关闭
    // 终止程序

   exit(signum);
}

void DispatchCore::slot_ServerCommandAnalysis(QJsonObject recvData)
{
    if(recvData.contains("CmdType"))
    {
        QJsonObject sendData;
        QString cmdtype = recvData.value("CmdType").toString();
        uint8_t nodeID = recvData.value("DeviceNo").toInt();
        // 设定某一参数
        if(cmdtype == "SETPARAMS")
        {
            uint32_t objectIndex = recvData.value("ObjectIndex").toInt();
            int32_t value = recvData.value("Value").toInt();
            emit sig_SetServoParam(nodeID,objectIndex,value);
        }
        // 探测指令，上报伺服所有的参数
        else if(cmdtype == "PROBE")
        {
            // 获取对应伺服的各种参数 并组装返回帧
            uint8_t deviceno = recvData.value("DeviceNo").toInt();
            uint8_t type = recvData.value("Type").toInt();
            if(type == 1)
                emit sig_ReadRwParams(deviceno);
        }
        else if(cmdtype == "MOVECMD")
        {
            emit sig_moveCmd(recvData);
        }
        else if(cmdtype == "INOUTCABCMD")
        {
            //下发新的指令
            if(ArvCommand::getInstance().isExCompleted == true)
            {
                mylog<<"get new InOutCabCmd";
                ArvCommand::getInstance().PortLocation_X = recvData.value("PortLocation_X").toInt();
                ArvCommand::getInstance().PortLocation_Y = recvData.value("PortLocation_Y").toInt();
                ArvCommand::getInstance().StorgeLocation_X = recvData.value("StorgeLocation_X").toInt();
                ArvCommand::getInstance().StorgeLocation_Y = recvData.value("StorgeLocation_Y").toInt();
                ArvCommand::getInstance().Type = recvData.value("Type").toInt();
                ArvCommand::getInstance().HaveNext = recvData.value("HaveNext").toBool();
                ArvCommand::getInstance().Face = recvData.value("Face").toInt();
                ArvCommand::getInstance().QRCode = "320121198601012233";//recvData.value("QRCode").toString();
                ArvCommand::getInstance().isDebug = recvData.value("IsDebug").toBool();
                ArvCommand::getInstance().isExCompleted = false;
                if(ArvCommand::getInstance().isDebug == true)
                    ArvCommand::getInstance().SetStep(ServoManager::Debug_StepStatus_CmdDoing);
                emit sig_startInOutCabCmd();
            }
            //调试进行下一步
            else if(ArvCommand::getInstance().isDebug == true)
            {
                //上一步执行完成才能进行下一步
                if(ArvCommand::getInstance().StepCnt == ServoManager::Debug_StepStatus_CmdOK){
                    mylog<<"Set InOutCmd Step Next";
                    g_DebugCondition.wakeAll();
                }
                //当前调试步骤未执行完成，回报警告
                else{
                    mylog<<"Current InOutCmd not exed";
                }
            }
            //不是调试指令，则上一条指令未执行完成，回报警告
            else
            {

            }
        }
        else if(cmdtype == "QRLOCATE")
        {
            //下发新的指令
            if(QRLocateCommand::getInstance().isExCompleted == true)
            {
                mylog<<"get new QRLocateCmd!";
                QRLocateCommand::getInstance().totalLayer = recvData.value("TotalLayer").toInt();
                QRLocateCommand::getInstance().totalSub = recvData.value("TotalSub").toInt();
                QRLocateCommand::getInstance().portLayer = recvData.value("PortLayer").toInt();
                QRLocateCommand::getInstance().isDebug = recvData.value("Debug").toBool();
                QRLocateCommand::getInstance().subWidth.clear();
                QJsonArray array = recvData.value("SubWidth").toArray();
                mylog<<"subwidth:"<<array;
                foreach (const QJsonValue& var, array) {
                    QRLocateCommand::getInstance().subWidth.push_back(var.toInt());
                }
                QRLocateCommand::getInstance().isExCompleted = false;
                if(QRLocateCommand::getInstance().isDebug == true)
                    QRLocateCommand::getInstance().SetStep(ServoManager::Debug_StepStatus_CmdDoing);
                emit sig_startQRLocateCmd();
            }
            //调试进行下一步
            else if(QRLocateCommand::getInstance().isDebug == true)
            {
                //上一步执行完成才能进行下一步
                if(QRLocateCommand::getInstance().StepCnt == ServoManager::Debug_StepStatus_CmdOK)
                {
                    mylog<<"Set QRLocate Step Next";
                    QRLocateCommand::getInstance().SetStep(ServoManager::Debug_StepStatus_CmdNext);
                }
                //当前调试步骤未执行完成，回报警告
                else
                {
                    mylog<<"Current QRLocate not exed";
                }
            }
            //不是调试指令，则上一条指令未执行完成，回报警告
            else
            {

            }
        }
        else if(cmdtype == "IMGCMD"){
            emit sig_imgCmd();
        }
    }
    // 接收数据有误
    else
    {

    }
}



